package com.longtop.framework.sys.file.supports;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.io.FileUtils;

import com.longtop.framework.util.StringUtil;

/**
 * Filename: FileControl.java <br>
 * Ttitle: 文件操作类<br>
 * Description:包括文件的创建。删除，更新内容等..<br>
 * Copyright: Copyright (c) 2001-2004 BlueStar,Inc.All Rights Reserved. <br>
 * Company: bluestar <br>
 * Author: <a href="mailto:lanxingsc@163.com">wuyang</a> <br>
 * Telephone: 86-28-85239210 <br>
 * Date: 2004-9-2 <br>
 * Time: 10:14:07 <br>
 * Version: 2.0.0 <br>
 */

public class FileControl {

	/**
	 * 相对路经
	 */
	private String path = "";

	/**
	 * 根路经
	 */
	private String rootPath = "";

	/**
	 * 文件名
	 */
	private String fileName = "";
	/**
	 * 文件
	 */
	private File myFile = null;

	/**
	 * 返回当前文件
	 * 
	 * @return
	 */
	public File getMyFile() {
		return myFile;
	}

	/**
	 * 设置要操作的文件
	 * 
	 * @param myFile
	 */
	public void setMyFile(File myFile) {
		this.myFile = myFile;
	}

	/**
	 * 构建器
	 */
	public FileControl() {
	}

	/**
	 * 构建器
	 * 
	 * @param request
	 *            取得根相对路经
	 * @param path
	 *            自定义路径
	 * @param fileName
	 *            文件名
	 */
	public FileControl(HttpServletRequest request, String path, String fileName) {
		path = StringUtil.replace(path, "\"", "/");
		path = StringUtil.replace(path, "//", "/");
		path = StringUtil.replace(path, "\\", "/");
		if (!StringUtil.isEndWith(path, "/"))
			path += "/";

		this.rootPath = request.getSession().getServletContext().getRealPath(path + fileName);
		this.path = path;
		this.fileName = fileName;
		this.myFile = new File(rootPath);
	}

	/**
	 * 构建器(文件夹)
	 * 
	 * @param request
	 *            取得根相对路经
	 * @param path
	 *            自定义路径（包括文件名）
	 */
	public FileControl(HttpServletRequest request, String path) {
		path = StringUtil.replace(path, "\"", "/");
		path = StringUtil.replace(path, "//", "/");
		path = StringUtil.replace(path, "\\", "/");
		this.path = request.getSession().getServletContext().getRealPath(path);
		this.myFile = new File(path);

	}

	/**
	 * 构建器
	 * 
	 * @param path
	 *            自定义路径
	 * @param fileName
	 */
	public FileControl(String path, String fileName) {
		path = StringUtil.replace(path, "\"", "/");
		path = StringUtil.replace(path, "//", "/");
		path = StringUtil.replace(path, "\\", "/");
		if (!StringUtil.isEndWith(path, "/"))
			path += "/";
		this.path = path;
		this.fileName = fileName;
		File file = new File(path + fileName);
		this.myFile = file;
	}

	/**
	 * 构建器(文件夹)
	 * 
	 * @param path
	 *            自定义路径（包括文件名）
	 */
	public FileControl(String path) {
		path = StringUtil.replace(path, "\"", "/");
		path = StringUtil.replace(path, "//", "/");
		path = StringUtil.replace(path, "\\", "/");
		File file = new File(path);
		this.fileName = file.getName();
		this.path = file.getPath();
		this.myFile = file;

	}

	/**
	 * 构建器
	 * 
	 * @param file
	 */
	public FileControl(File file) {
		this.myFile = file;
	}

	/**
	 * 文件的创建 如果路经不存在，则自动创建路经
	 * 
	 * @return
	 * @throws FileUtilException
	 */
	public boolean createFile() throws FileUtilException {
		if (myFile == null) {
			throw new FileUtilException("请指定要创建的文件");
		} else if (myFile.isDirectory()) {
			createDirectory();
			return true;
		} else {
			try {
				createDirectory();
				myFile.createNewFile();
				return true;
			} catch (IOException e) {
				throw new FileUtilException("文件创建失败", e);
			}
		}
	}

	/**
	 * 删除文件，如果是文件夹不能删除
	 * 
	 * @return
	 * @throws FileUtilException
	 */
	public boolean deleteFile() throws FileUtilException {
		if (this.myFile == null)
			throw new FileUtilException("你未指定你要删除的文件");
		else if (myFile.isDirectory())
			throw new FileUtilException("你指定的是一个文件夹,不能删除");
		else if (myFile.isFile())
			return myFile.delete();
		else
			throw new FileUtilException("你指定的文件不存在");
	}

	/**
	 * 取得子文件夹所有文件或文件夹
	 * 
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public List getFileList() {
		List l = new ArrayList();
		if (myFile.isDirectory()) {
			File[] f = myFile.listFiles();
			for (int k = 0; k < f.length; k++) {
				if (f[k].isFile()) {
					l.add(f[k]);
				}
			}
		}
		return l;
	}

	/**
	 * 创建文件夹
	 * 
	 * @return
	 */
	public boolean createDirectory() {

		File tempFile = null;
		String tempFilePath = "";
		if (this.myFile.isFile())
			tempFile = myFile;
		else
			tempFile = myFile.getParentFile();
		String path = StringUtil.getString(tempFile.getAbsolutePath(), "");
		path = StringUtil.replace(path, "\"", "/");
		path = StringUtil.replace(path, "//", "/");
		path = StringUtil.replace(path, "\\", "/");
		String[] fileName = StringUtil.split(path, "/");
		for (int kk = 0; kk < fileName.length; kk++) {
			tempFilePath += fileName[kk] + "/";
			if (!tempFilePath.startsWith("/") && tempFilePath.indexOf(":") != 1) {
				tempFilePath = "/" + tempFilePath;
			}
			tempFile = new File(tempFilePath);
			tempFile.mkdir();
		}
		return true;
	}

	/**
	 * 删除文件夹及其中所有内容
	 * 
	 * @return
	 * @throws FileUtilException
	 */
	public boolean deleteDirectory() throws FileUtilException {
		if (myFile == null) {
			throw new FileUtilException("你未指定你要删除的文件夹");
		} else if (myFile.isFile()) {
			throw new FileUtilException("你指定的是一个文件");
		} else if (myFile.isDirectory()) {
			try {
				FileUtils.deleteDirectory(myFile);
				return true;
			} catch (Exception e) {
				e.printStackTrace();
				return false;
			}

		} else {
			throw new FileUtilException("你指定的文件夹不存在");
		}
	}

	/**
	 * 更新文件内容
	 * 
	 * @param fileText
	 * @return
	 * @throws FileUtilException
	 */
	public boolean updateFile(String fileText) throws FileUtilException {
		myFile.delete();
		if (writeFile(fileText)) {
			return true;
		} else {
			return false;
		}
	}

	/**
	 * 写入文件
	 * 
	 * @param str
	 * @return
	 * @throws FileUtilException
	 */
	public boolean writeFile(String str) throws FileUtilException {
		if (myFile == null) {
			throw new FileUtilException("请指定要与入的文件");
		} else if (!myFile.isFile()) {
			throw new FileUtilException("对不起，你指定的不是文件");
		}
		try {
			FileUtils.writeStringToFile(myFile, str);
		} catch (IOException e) {
			throw new FileUtilException("写入文件失败", e);
		}
		return true;
	};

	/**
	 * 写入文件
	 * 
	 * @param is
	 * @return
	 * @throws FileUtilException
	 */
	public boolean writeFile(InputStream is) throws FileUtilException {
		if (myFile == null) {
			throw new FileUtilException("请指定要与入的文件");
		} else if (!myFile.isFile()) {
			throw new FileUtilException("对不起，你指定的不是文件");
		}
		try {
			FileOutputStream out = new FileOutputStream(myFile);
			byte data[] = new byte[is.available()];
			is.read(data);
			out.write(data);
			is.close();
			out.close();
		} catch (IOException e) {
			throw new FileUtilException("写入文件失败", e);
		}
		return true;
	};

	/**
	 * 读取文件内容
	 * 
	 * @return
	 * @throws FileUtilException
	 */
	public String readFile() throws FileUtilException {
		String tempStr = "", tempStr2 = "";
		if (myFile == null) {
			throw new FileUtilException("请指定要读取的文件");
		} else if (!myFile.isFile()) {
			throw new FileUtilException("对不起，你读取的不是文件");
		}
		try {
			BufferedReader in = new BufferedReader(new InputStreamReader(new FileInputStream(myFile), "UTF-8"));
			// BufferedReader in = new BufferedReader(new FileReader(this.myFile));
			while ((tempStr = in.readLine()) != null) {
				tempStr2 += tempStr + "/n";
			}
			in.close();
		} catch (IOException e) {
			throw new FileUtilException("读取文件失败", e);
		}
		return tempStr2;
	}

	/**
	 * 以StringBuffer的形式得到文件
	 * 
	 * @return
	 * @throws FileUtilException
	 */
	public StringBuffer readFileBuffer() throws FileUtilException {
		StringBuffer tempStr = new StringBuffer();
		String line = "";
		if (myFile == null) {
			throw new FileUtilException("请指定要读取的文件");
		} else if (!myFile.isFile()) {
			throw new FileUtilException("对不起，你读取的不是文件");
		}
		try {
			BufferedReader in = new BufferedReader(new FileReader(this.myFile));
			while ((line = in.readLine()) != null) {
				tempStr.append(line + "/n");
			}
			in.close();
		} catch (IOException e) {
			throw new FileUtilException("写入文件失败", e);
		}
		return tempStr;
	}

	/**
	 * 读取文件内容
	 * 
	 * @return
	 * @throws FileUtilException
	 */
	public byte[] readFileByte() throws FileUtilException {
		String tempStr = "", tempStr2 = "";
		if (myFile == null) {
			throw new FileUtilException("请指定要读取的文件");
		} else if (!myFile.isFile()) {
			throw new FileUtilException("对不起，你读取的不是文件");
		}
		try {
			BufferedReader in = new BufferedReader(new FileReader(this.myFile));
			while ((tempStr = in.readLine()) != null) {
				tempStr2 += tempStr;
			}
			in.close();
		} catch (IOException e) {
			throw new FileUtilException("写入文件失败", e);
		}
		return tempStr2.getBytes();
	}

	/**
	 * 复制文件
	 * 
	 * @param taget
	 *            目标位置 路径
	 * @param fileName
	 *            目标文件名
	 * @throws FileUtilException
	 */
	public void copyFile(String taget, String fileName) throws FileUtilException {

		taget = StringUtil.replace(taget, "\"", "/");
		taget = StringUtil.replace(taget, "//", "/");
		taget = StringUtil.replace(taget, "\\", "/");

		if (!taget.endsWith("/")) {
			taget += "/";
		}
		taget = taget + fileName;
		File tagetFile = new File(taget);
		if (!tagetFile.isFile()) {
			throw new FileUtilException("目标地址有问题");
		}
		try {
			FileUtil.copy(myFile, tagetFile);
		} catch (IOException e) {
			e.printStackTrace();
			throw new FileUtilException("复制文件出错", e);
		}
	}

	/**
	 * 复制文件
	 * 
	 * @param taget
	 *            目标位置
	 * @throws FileUtilException
	 */
	public void copyFile(String taget) throws FileUtilException {
		copyFile(taget, myFile.getName());
	}

	/**
	 * 移动文件
	 * 
	 * @param taget
	 *            目标位置
	 * @param fileName
	 *            目标文件名
	 * @throws FileUtilException
	 */
	public void moveFile(String taget, String fileName) throws FileUtilException {
		taget = StringUtil.replace(taget, "\"", "/");
		taget = StringUtil.replace(taget, "//", "/");
		taget = StringUtil.replace(taget, "\\", "/");
		if (!taget.endsWith("/")) {
			taget += "/";
		}
		taget = taget + fileName;
		File tagetFile = new File(taget);
		if (!tagetFile.isFile()) {
			throw new FileUtilException("目标地址有问题");
		}
		try {
			FileUtils.moveFile(myFile, tagetFile);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			throw new FileUtilException("移动文件出错", e);
		}
	}

	/**
	 * 移动文件
	 * 
	 * @param taget
	 *            目标位置
	 * @throws FileUtilException
	 */
	public void moveFile(String taget) throws FileUtilException {
		moveFile(taget, myFile.getName());
	}

	public static void main(String[] a) {
		FileControl ss = new FileControl("E:\\tomcat\\webapps\\thgk\\upload\\excel1111111\\2009\\7\\12", "124733598025010000.xls");
		ss.deleteFile();
	}
}
